<template>
  <div>
    <!--面包屑导航-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!--卡片视图-->
    <el-card>
      <!--添加角色按钮区域-->
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>

      </el-row>

      <!--角色列表区域-->
      <el-table
        :data="roleList"
        stripe
        border>
        <!--展开列-->
        <el-table-column type="expand">
          <div slot-scope="scope" class="rights-row-container">
            <el-row v-for="item1 in scope.row.children" :key="item1.id">
              <!--渲染一级权限-->
              <el-col :span="5">
                <el-tag
                  closable
                  @close="removeRightById(scope.row,item1.id)"
                >{{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!--渲染二级、三级权限-->
              <el-col :span="19" class="rights-second-container">
                <!--通过for循环嵌套渲染二级权限-->
                <el-row v-for="(item2,i2) in item1.children" :key="item2.id" :style="i2===0?{'border-top':'none'}:''">
                  <!--二级权限-->
                  <el-col :span="6">
                    <el-tag closable
                            @close="removeRightById(scope.row,item2.id)"
                            type="success">{{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!--三级权限-->
                  <el-col :span="13">
                    <!--通过for循环渲染三级权限-->
                    <el-tag type="warning"
                            closable
                            @close="removeRightById(scope.row,item3.id)"
                            v-for="item3 in item2.children">
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </div>
        </el-table-column>
        <!--索引列-->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" icon="el-icon-edit">编辑</el-button>
            <el-button type="warning" size="mini" icon="el-icon-delete">删除</el-button>
            <el-button
              @click="showSetRightDialog(scope.row)"
              type="danger" size="mini" icon="el-icon-setting">分配权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!--分配权限的对话框-->
    <el-dialog title="分配权限"
               @close="setRightDialogClosed"
               :visible.sync="setRightDialogVisible"
               width="50%">
      <!--树形控件-->
      <el-tree :data="rightsList"
               :props="treeProps"
               node-key="id"
               default-expand-all
               :default-checked-keys="defKeys"
               ref="treeRef"
               show-checkbox></el-tree>
      <span slot="footer" class="dialog-footer">
    <el-button @click="setRightDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="allotRights">确 定</el-button>
  </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
  name: "Roles",
  data() {
    return {
      //所有角色列表数据
      roleList: [],
      //控制权限对话框的显示与隐藏
      setRightDialogVisible: false,
      //所有权限的数据
      rightsList: [],
      //树形控件的属性绑定对象
      treeProps: {
        label: "authName",
        children: "children"
      },
      //权限三级节点id数组
      defKeys: [],
      //即将分配权限的roleId
      roleId: "",
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    //获取所有角色的列表
    async getRoleList() {
      const {data: res} = await this.$http.get("/roles");
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error("获取角色列表失败：" + res.meta.msg)
      this.roleList = res.data
    },
    //根据id删除权限
    async removeRightById(role, rightId) {
      const result = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (result !== "confirm") return this.$message.info("取消了删除")
      const {data: res} = await this.$http.delete(`/roles/${role.id}/rights/${rightId}`)
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error("删除失败:" + res.meta.msg)
      this.$message.success("删除成功")
      role.children = res.data
    },
    //显示分配权限对话框
    async showSetRightDialog(role) {
      //role保存到data中
      this.roleId = role.id
      //获取所有权限的数据（树形）
      const {data: res} = await this.$http.get("/rights/" + "tree");
      console.log(res)
      //把获取到的权限数据保存到data中
      this.rightsList = res.data
      //递归获取三级节点的id,并将id保存到data中
      this.getLeafKeys(role, this.defKeys)

      //权利分配弹窗可见
      this.setRightDialogVisible = true
    },
    //通过递归获取角色三级权限id,并保持到defKeys中
    getLeafKeys(node, arr) {
      //如果当前node节点不包含children属性，则是三级节点
      if (!node.children) return arr.push(node.id)
      //如果当前node节点包含children属性，则遍历递归
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    //监听分配权限对话框关闭事件
    setRightDialogClosed() {
      //清空三级节点id
      this.defKeys = []
    },
    //提交权限分配
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      //将id数组转成以逗号分隔的字符串
      const idStr = keys.join(',')
      const {data: res} = await this.$http.post(`roles/${this.roleId}/rights`, {rids: idStr})
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error("权限分配失败:" + res.meta.msg)
      this.$message.success("分配权限成功")
      //获取权限数据
      this.getRoleList()
      //隐藏分配权限对话框
      this.setRightDialogVisible=false
    }
  },


}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}

//一级权限分割线样式
.rights-row-container > .el-row {
  border-bottom: 1px solid #eee;
  display: flex;
  align-items: center;
}

.rights-row-container:first-child {
  border-top: 1px solid #eee;
}

//二级权限分割线样式
.rights-second-container > .el-row {
  border-top: 1px solid #eee;
  display: flex;
  align-items: center;
}

.rights-second-container-last-child {
  border-top: none;
}
</style>
